import axios from 'axios'
import { Notification } from 'element-ui'
import util from '@/utils/util'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 30000
})

const err = error => {
  if (error.response) {
    const data = error.response.data
    const status = error.response.status
    if (status === 401 && error.config.url !== 'logout') {
      util.removeUserInfo()
      setTimeout(() => {
        window.location.reload()
      }, 500)
    } else if (status === 400 || status === 403 || status === 500) {
      Notification.error({
        title: '错误提示',
        message: data.msg ? data.msg : '服务器发生错误'
      })
    }
    return Promise.reject(data)
  }
  return Promise.reject(error)
}

// 请求拦截器
service.interceptors.request.use(config => {
  const token = util.getToken()
  if (token) {
    config.headers.Authorization = token
  }
  if (config.url === 'login') {
    const clientInfo = util.getClientInfo()
    for (const key in clientInfo) {
      config.headers[key.replace('_', '-')] = clientInfo[key]
    }
  }
  return config
}, err)

// 响应拦截器
service.interceptors.response.use(response => {
  return response.data
}, err)

export { service as axios }
